﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using LRSTaxServices.Biz;
using LRSTaxServices.Common;

public partial class Controls_SubAdminCreation : System.Web.UI.UserControl
{


    #region Types - None


    #endregion

    #region Members - None


    #endregion

    #region Constants

    private const string PROP_MODE = "__UserViewEdit::Mode";
    private const string PROP_PSWD_CHANGED = "__UserViewEdit::PwdChanged";
    private const string PROP_ROLES_CHANGED = "__UserViewEdit::RolesChanged";

    #endregion

    #region Public Properties

    /// <summary>
    /// Gets / sets the SubAdmin data source object.
    /// </summary>
    public SubAdmin DataSourceUser
    {
        get
        {
            if (_dataSource == null)
            {
                if (DataSourceUserRequested != null)
                    DataSourceUserRequested(this, EventArgs.Empty);
            }
            return (_dataSource);
        }
        set
        {
            if (_dataSource != value)
            {
                _dataSource = value;
                // OnDataSourceUserChanged();
            }
        }
    } private SubAdmin _dataSource = null;

    /// <summary>
    /// Gets / sets the AppUserRolesCollection data source object.
    /// </summary>
    public SubAdminRoleCollection DataSourceRoles
    {
        get
        {
            if (_dataSourceRoles == null)
            {
                if (DataSourceRolesRequested != null)
                    DataSourceRolesRequested(this, EventArgs.Empty);
            }
            return (_dataSourceRoles);
        }
        set
        {
            if (_dataSourceRoles != value)
            {
                _dataSourceRoles = value;
                // OnDataSourceRolesChanged();
            }
        }
    } private SubAdminRoleCollection _dataSourceRoles = null;


    /// <summary>
    /// Gets / sets the control's mode.
    /// </summary>
    public ViewEditMode Mode
    {
        get { return (ViewState[ClientID + PROP_MODE] is ViewEditMode ? (ViewEditMode)ViewState[ClientID + PROP_MODE] : ViewEditMode.View); }
        private set { ViewState[ClientID + PROP_MODE] = value; }
    }


    /// <summary>
    /// True iff the text of the Password and/or ConfirmPassword UI elements have been modified.
    /// </summary>
    public bool PasswordChanged
    {
        get { return (ViewState[ClientID + PROP_PSWD_CHANGED] is bool ? (bool)ViewState[ClientID + PROP_PSWD_CHANGED] : false); }
        private set { ViewState[ClientID + PROP_PSWD_CHANGED] = value; }
    }


    /// <summary>
    /// True iff one or more of the Roles UI elements have been modified.
    /// </summary>
    public bool RolesChanged
    {
        get { return (ViewState[ClientID + PROP_ROLES_CHANGED] is bool ? (bool)ViewState[ClientID + PROP_ROLES_CHANGED] : false); }
        set { ViewState[ClientID + PROP_ROLES_CHANGED] = value; }
    }

    #endregion

    #region Public Events

    public event EventHandler DataSourceUserRequested;

    public event EventHandler DataSourceRolesRequested;

    #endregion

    #region Public Methods

    /// <summary>
    /// Method initializes and binds the controls UI elements to the properties of the specified object instance.
    /// </summary>
    public bool DataBind(SubAdmin user, SubAdminRoleCollection permittedRoles)
    {
        return (DataBind(user, permittedRoles, Mode));
    }


    /// <summary>
    /// Method initializes and binds the controls UI elements to the properties of the specified object instance.
    /// </summary>
    public bool DataBind(SubAdmin user, SubAdminRoleCollection permittedRoles, ViewEditMode mode)
    {
        DataSourceUser = user;
        DataSourceRoles = permittedRoles;
        Mode = mode;

        LoadRolesCheckBoxList();

        PasswordChanged = false;
        RolesChanged = false;

        SetLayout(Mode);

        UpdateData(UpdateDirection.Obj_To_UI);

        return (true);
    }


    /// <summary>
    /// Method causes the control to update its DataSource(s) with the values in the UI elements.
    /// </summary>
    public bool EndEdit()
    {
        if (PasswordChanged)
        {
            string pwdErrMsg, confirmPwdErrMsg;
            DataSourceUser.Password = SubAdmin.HashPassword(txtpassword.Text.Trim());
            if (!SubAdmin.ValidatePasswordEntry(txtpassword.Text, txtconfirmpassword.Text, out pwdErrMsg, out confirmPwdErrMsg))
            {
                //        lblPwdError.Text = pwdErrMsg;
                //        lblPwdError.Visible = pwdErrMsg.Length > 0;
                //        lblConfirmPwdError.Text = confirmPwdErrMsg;
                //        lblConfirmPwdError.Visible = confirmPwdErrMsg.Length > 0;
                return (false);
            }
            else
            {
                //lblPwdError.Visible = false;
                //lblConfirmPwdError.Visible = false;
                DataSourceUser.Password = SubAdmin.HashPassword(txtpassword.Text.Trim());
            }
        }
        CaptchaControl1.ValidateCaptcha(txtcaptcha.Text.Trim());
        if (CaptchaControl1.UserValidated)
        {
            UpdateData(UpdateDirection.UI_To_Obj);
            return (true);
        }
        else
        {
            lblcaptcha.Text = "Please enter the correct code of the image...";
            lblcaptcha.ForeColor = System.Drawing.Color.Red;
            return (false);
        }


    }


    /// <summary>
    /// Method causes the control to reject changes made in the UI by rebinding the UI elements to the DataSource(s).
    /// </summary>
    public void CancelEdit()
    {
        PasswordChanged = false;
        RolesChanged = false;

        UpdateData(UpdateDirection.Obj_To_UI);
    }


    /// <summary>
    /// Method sets the control's ViewEditMode.
    /// </summary>
    public void SetViewEditMode(ViewEditMode mode)
    {
        Mode = mode;
        SetLayout(Mode);
    }

    #endregion

    #region Event Handlers

    #region Page Load

    protected void Page_Load(object sender, EventArgs evt)
    {
        if (!Page.IsPostBack)
        {
            InitMaxFieldLengths();
        }
    }

    #endregion

    #region txtPasswords_TextChanged

    protected void txtpassword_TextChanged(object sender, EventArgs e)
    {
        if ((txtpassword.Text.Trim().Length > 0) || (txtconfirmpassword.Text.Trim().Length > 0))
        {
            PasswordChanged = true;
            return;
        }
    }

    #endregion

    #region Roles Checkbox List Selected

    protected void cboroleslist_SelectedIndexChanged(object sender, EventArgs e)
    {
        RolesChanged = true;
    }

    #endregion

    #endregion

    #region Privates

    #region SetLayout

    private void SetLayout(ViewEditMode mode)
    {
        switch (mode)
        {
            case ViewEditMode.View:
                //pnladminview.Visible = true;
                pnladmincreation.Visible = false;
                break;

            case ViewEditMode.Edit:
                //pnladminview.Visible = false;
                pnladmincreation.Visible = true;
                break;
        }
    }

    #endregion

    #region InitMaxFieldLengths

    private void InitMaxFieldLengths()
    {
        txtconfirmpassword.MaxLength = SubAdmin.PasswordMaxLength;
        txtemailaddress.MaxLength = SubAdmin.EmailAddressMaxLength;
        txtfirstname.MaxLength = SubAdmin.FirstNameMaxLength;
        txtlastname.MaxLength = SubAdmin.LastNameMaxLength;
        txtmobilephone.MaxLength = SubAdmin.MobilePhoneMaxLength;
        txtpassword.MaxLength = SubAdmin.PasswordMaxLength;
        //combotoc.Text.Length = SubAdmin.TitleOfCourtesyMaxLength;
        txtusername.MaxLength = SubAdmin.UserLoginMaxLength;
        txtworkphone.MaxLength = SubAdmin.WorkPhoneMaxLength;
    }

    #endregion

    #region UpdateDate

    public void UpdateData(UpdateDirection updatedir)
    {
        if (DataSourceUser == null)
            return;

        bool addingNew = (DataSourceUser.ObjState == BOBase.ObjectState.Added);

        if (updatedir == UpdateDirection.Obj_To_UI)
        {
            //View Elements





            //Edit Elements

            if (!String.IsNullOrEmpty(DataSourceUser.TitleOfCourtesy))
            {
                combotoc.SelectedValue = DataSourceUser.TitleOfCourtesy;
                //ListItem item = combotoc.Items.FindByText(DataSourceUser.TitleOfCourtesy);
                //if (item != null)
                //    item.Selected = true;
                //else combotoc.Text = DataSourceUser.TitleOfCourtesy;
            }
            else
            {
                combotoc.SelectedValue = "Select.";
                //combotoc.Items[0].Selected = true;
            }

            txtfirstname.Text = DataSourceUser.FirstName;
            txtlastname.Text = DataSourceUser.LastName;
            txtemailaddress.Text = DataSourceUser.EmailAddress;
            txtusername.Text = DataSourceUser.UserLogin;
            if (addingNew)
            {
                txtpassword.Text = "";
                txtconfirmpassword.Text = "";
            }
            else
            {
                txtpassword.Text = "**********";
                txtconfirmpassword.Text = "**********";
            }
            txtworkphone.Text = DataSourceUser.WorkPhone;
            txtmobilephone.Text = DataSourceUser.MobilePhone;




            if (cboroleslist.Items.Count == 0)
                LoadRolesCheckBoxList();

            foreach (ListItem item in cboroleslist.Items)
            {
                SubAdminRoleCollection sar = DataSourceUser.Roles.FindByRoleID(int.Parse(item.Value));
                item.Selected = (sar.Count != 0);
            }



        }
        else
        {
            if ((combotoc.Text != null) && (combotoc.Text.Trim().Length > 0))
                DataSourceUser.TitleOfCourtesy = combotoc.Text.Trim();
            else DataSourceUser.TitleOfCourtesy = null;

            //if ((combousertype.Text != null) && (combousertype.Text.Trim().Length > 0))
            //    DataSourceUser.UserType = combousertype.Text.Trim();
            //else DataSourceUser.UserType = null;

            if (txtfirstname.Text.Trim().Length > 0)
                DataSourceUser.FirstName = txtfirstname.Text.Trim();
            else DataSourceUser.FirstName = null;

            if (txtlastname.Text.Trim().Length > 0)
                DataSourceUser.LastName = txtlastname.Text.Trim();
            else DataSourceUser.LastName = null;

            if (txtemailaddress.Text.Trim().Length > 0)
            {
                DataSourceUser.EmailAddress = txtemailaddress.Text.Trim();
            }
            else DataSourceUser.EmailAddress = null;

            if (txtusername.Text.Trim().Length > 0)
            {
                DataSourceUser.UserLogin = txtusername.Text.Trim();
            }
            else DataSourceUser.UserLogin = null;

            // Password changes are handled in EndEdit();

            if (txtworkphone.Text.Trim().Length > 0)
            {
                DataSourceUser.WorkPhone = txtworkphone.Text.Trim();
            }
            else
            {
                DataSourceUser.WorkPhone = null;
            }

            if (txtmobilephone.Text.Trim().Length > 0)
            {
                DataSourceUser.MobilePhone = txtmobilephone.Text.Trim();
            }
            else
            {
                DataSourceUser.MobilePhone = null;
            }

            if (RolesChanged)
            {
                DataSourceUser.Roles.Clear();
                foreach (ListItem item in cboroleslist.Items)
                {
                    if (item.Selected)
                    {
                        int roleID;
                        if (!Int32.TryParse(item.Value, out roleID))
                            throw new ApplicationException("The selected RoleID could not be converted to an Int32.");
                        SubAdminRole subadminrole = SubAdminRole.CreateNew(DataSourceUser.UserID, (Schema.UserRoles)roleID);
                        DataSourceUser.Roles.Add(subadminrole);
                    }
                }
            }

            DataSourceUser.IsActive = chkboxIsActive.Checked;
        }

    }

    #endregion

    #region LoadRolesCheckBoxList

    protected void LoadRolesCheckBoxList()
    {

        cboroleslist.Items.Clear();

        foreach (Role role in Role.GetAllRoles())
        {
            ListItem item = new ListItem(role.RoleName, role.LU_RoleID.ToString());
            cboroleslist.Items.Add(item);
        }
    }

    #endregion

    #endregion



    
}
